package com.cimr.controller.user;


import com.cimr.comm.dto.HttpResult;
import com.cimr.comm.dto.LayuiTableData;
import com.cimr.comm.po.Group;
import com.cimr.comm.po.Permission;
import com.cimr.comm.po.User;
import com.cimr.comm.service.GroupService;
import com.cimr.comm.service.PermissionService;
import com.cimr.comm.service.UserService;
import com.cimr.comm.token.TokenUtil;
import com.cimr.comm.util.IdUtil;
import com.cimr.dto.PermissionTree;
import com.cimr.po.file.UnitFile;
import com.cimr.service.file.UnitFileService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zengfan on 2017/12/26.
 */
@Controller
@RequestMapping("/user/ajax")
public class UserManagementAjaxController{
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UnitFileService unitFileService;
    @Autowired
    private GroupService groupService;

    /**
     *@auther zengfan
     *@date 2017/12/27 14:57
     *@params
     * @param
     * @param theme 换肤主题（json类型存储）
     *
     **/
    @RequestMapping({"saveSkin"})
    @ResponseBody
    public HttpResult saveSkin(String theme) {

        String userId = TokenUtil.getUserId();
        int resultStatus1;
        resultStatus1 = userService.updateUser(userId, null, null, 1, null, null, null, null, null, null, null, theme, null);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }
        return result;
    }
    @RequestMapping({"getUserManagerList"})
    @ResponseBody
    public LayuiTableData getUserManagerList(@RequestParam(required = true,defaultValue = "1") Integer page, @RequestParam(required = false,defaultValue = "10") Integer limit, @RequestParam(required = false) String fullname) {

        LayuiTableData result = new LayuiTableData();

        User currentUser = TokenUtil.getToken();
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(currentUser.getGroupId());
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            PageHelper.startPage(page.intValue(), limit.intValue());
            List list = userService.selectList(fullname, groupIds);
            if (list!=null && list.size()>0) {
                PageInfo pageInfo = new PageInfo(list);
                List list1 = this.userService.selectList(fullname, groupIds);
                result.setCount(list1.size());
                result.setData(pageInfo.getList());
            }
        }
        result.setCode(Integer.valueOf(0));
        result.setMsg("");
        return result;
    }

    @RequestMapping({"getUserById"})
    @ResponseBody
    public HttpResult getUserById(@RequestParam(required = true) String id) {
        Map map = new HashMap();
        User user = this.userService.getUserById(id);
        map.put("unitFile",unitFileService.selectById_common(user.getAvatar()));
        map.put("user",user);
        HttpResult result = new HttpResult(true, "");
        result.setData(map);
        return result;
    }

    @RequestMapping({"saveUser"})
    @ResponseBody
    public HttpResult saveUser(HttpSession session, String fileJson, String id, String pswd, String username, String fullname,
                               String phone, String email, String comment, Float orderId, String groupId, String groupName, String theme) {

        String realPath = session.getServletContext().getRealPath("/");

        int resultStatus1;
        if (id != null && !"".equals(id)) {
            User user = userService.getUserById(id);
            unitFileService.deleteFile(user.getAvatar(),TokenUtil.getUserId());
            List<UnitFile> list = unitFileService.uploadFiles(fileJson,realPath,null,null,null,TokenUtil.getUserId());
            if (list!=null) {
                resultStatus1 = this.userService.updateUser(id, username, (String)null, 1, fullname, phone, email, comment, orderId, groupId, groupName, theme,list.get(0).getId());
            } else {
                resultStatus1 = this.userService.updateUser(id, username, (String)null, 1, fullname, phone, email, comment, orderId, groupId, groupName, theme,null);
            }

        } else {
            List<UnitFile> list = unitFileService.uploadFiles(fileJson,realPath,null,null,null,TokenUtil.getUserId());
            if (list!=null) {
                resultStatus1 = this.userService.insertUser(IdUtil.getId() + "", username, pswd, 1, fullname, phone, email, comment, orderId, groupId, groupName,theme,list.get(0).getId());
            } else {
                resultStatus1 = this.userService.insertUser(IdUtil.getId() + "", username, pswd, 1, fullname, phone, email, comment, orderId, groupId, groupName,theme,null);
            }
        }
        HttpResult result = new HttpResult(true, "");
        if (resultStatus1 == 0) {
            result.setSuccess(false);
        }

        return result;
    }

    @RequestMapping({"deleteUser"})
    @ResponseBody
    public HttpResult deleteUser(@RequestParam(required = true) String id) {
        int resultStatus = this.userService.deleteUser(id);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus == 0) {
            result.setSuccess(false);
        }

        return result;
    }
    /**
     *@auther zengfan
     *@date 2018/1/16 9:14
     *@params  * @param null
     *通过username查询user表
     **/
    @RequestMapping({"getUserByUserName"})
    @ResponseBody
    public HttpResult getUserByUserName( String userName) {
        User user = this.userService.getByUsername(userName);
        HttpResult result = new HttpResult(true, "");
        result.setData(user);
        return result;
    }
    /**
     *@auther zengfan
     *@date 2018/1/16 9:14
     *@params  * @param null
     *在编辑时通过username查询user表，并排除当前的username的user
     **/
    @RequestMapping({"getUserByUserNameOutCurrent"})
    @ResponseBody
    public HttpResult getUserByUserNameOutCurrent(String id, String userName) {
        User user = this.userService.getByUsername(userName);
        HttpResult result = new HttpResult(true, "");
        if(user!=null){
            if (user.getId().equals(id)){
                result.setData(null);
            }else {
                result.setData(user);
            }
        }else{
            result.setData(null);
        }

        return result;
    }
    /**
    *@auther zengfan
    *@date 2018/1/25 17:12
    *@params  * @param null
    *List<Permission> getPermissionListByUserId
    **/
    @RequestMapping({"getPermissionListByUserId"})
    @ResponseBody
    public HttpResult getPermissionListByUserId(String id) {
        List<Permission> list = permissionService.getPermissionListByUserId(id);
        List<Permission> menuList = new ArrayList<>();
        List<Permission> operationList = new ArrayList<>();
        //操作菜单分离
        for(int i=0;i<list.size();i++){
            if (list.get(i).getPermissionType().equals("menu")){
                menuList.add(list.get(i));
            }
            if (list.get(i).getPermissionType().equals("operation")){
                operationList.add(list.get(i));
            }
        }
     //菜单组装为树结构
        PermissionTree menuTree = new PermissionTree();
        //一级、二级菜单分离菜单
        List<Permission> menuLevel_1_List = new ArrayList<>();
        List<Permission> menuLevel_2_List = new ArrayList<>();
        for(int i=0;i<menuList.size();i++){
            if(menuList.get(i).getLevel()==1){
                menuLevel_1_List.add(menuList.get(i));
            }
            if(menuList.get(i).getLevel()==2){
                menuLevel_2_List.add(menuList.get(i));
            }
        }
        // 菜单的树结构  二级菜单放入对应的父级(一级)菜单中并组装为PermissionTree类型
        List<PermissionTree> menuPtList = new ArrayList<>();
        for(int i=0;i<menuLevel_1_List.size();i++){
            PermissionTree pt_level_1 = new PermissionTree();
            pt_level_1.setName(menuLevel_1_List.get(i).getPermissionName());
            pt_level_1.setValue(menuLevel_1_List.get(i).getPermissionKey());
            List<PermissionTree> childList = new ArrayList<>();
            for(int j=0;j<menuLevel_2_List.size();j++){
                if(menuLevel_2_List.get(j).getParentId().equals(menuLevel_1_List.get(i).getId())){
                    PermissionTree childPt = new PermissionTree();
                    childPt.setName(menuLevel_2_List.get(j).getPermissionName());
                    childPt.setValue(menuLevel_2_List.get(j).getPermissionKey());
                    childList.add(childPt);
                }
            }
            pt_level_1.setChildren(childList);
            menuPtList.add(pt_level_1);
        }
        //操作的树结构
        List<PermissionTree> perPtList = new ArrayList<>();
        for(int i=0;i<operationList.size();i++){
            PermissionTree perPt = new PermissionTree();
            perPt.setName(operationList.get(i).getPermissionName());
            perPt.setValue(operationList.get(i).getPermissionKey());
            perPtList.add(perPt);
        }
        Map map = new HashMap();
        map.put("menu",menuPtList);
        map.put("permission",perPtList);
        HttpResult result = new HttpResult(true, "");
        result.setData(map);
        return result;
    }
}
